import { hasValue } from "components/advanced-search/utils";
import { Icon, Popover } from "antd";
import AdvancedTableFilterDropdown from "components/advanced-table/advanced-table-filter-dropdown";
import SVGIcon from "components/SVGIcon";
import React from "react";
import { messages } from "share/common";

class FilterButton extends React.Component {
  state = {
    dropdownVisible: {},
    searchParams: {},
  };

  onClose = () => {
    this.setState(
      { dropdownVisible: {} },
      this.props.refreshTableColumns && this.props.refreshTableColumns(["filterIcon"])
    );
  };

  onOpen = (key) => {
    this.setState({ dropdownVisible: { [key]: true } }, () => {
      //因为在列上，所以需要手动刷新ResizeTable的列属性
      this.props.refreshTableColumns && this.props.refreshTableColumns(["filterIcon"]);
    });
  };

  onSearch = (params) => {
    const { search, column } = this.props;
    this.setState({ dropdownVisible: { [column.dataIndex]: false }, searchParams: { ...params } });
    search && search({ ...column, ...params });
  };

  render() {
    const { column, columnSearchForm } = this.props;
    let filterDropdownRefs = {};
    const { dropdownVisible, searchParams } = this.state;
    let filtered = columnSearchForm.some((field) => hasValue(field, searchParams[field.id]));
    return (
      <span className="filter-button" onClick={() => this.onOpen(column.dataIndex, columnSearchForm)}>
        <Popover
          visible={dropdownVisible[column.dataIndex] || false}
          placement={"bottomLeft"}
          overlayClassName="advanced-table-filter-column-popover"
          title={
            <div className="advanced-table-filter-column-popover-title">
              {messages("common-1.key24") /*筛选条件*/}
              <Icon type="close" onClick={this.onClose} />
            </div>
          }
          content={
            <AdvancedTableFilterDropdown
              searchForm={columnSearchForm}
              onSearch={this.onSearch}
              onRef={(ref) => (filterDropdownRefs[column.dataIndex] = ref)}
            />
          }
          trigger="click"
          getPopupContainer={() => document.querySelector(".expense-apportion")}
        >
          <SVGIcon className={`filter-icon-wrapper ${filtered ? "filtered" : ""}`} type="table-filter" />
        </Popover>
      </span>
    );
  }
}

export default FilterButton;
